package com.tbl.modules.wms.controller.baseinfo;

import com.alibaba.fastjson.JSON;
import com.tbl.common.utils.*;
import com.tbl.modules.platform.constant.LogActionConstant;
import com.tbl.modules.platform.controller.AbstractController;
import com.tbl.modules.platform.service.system.LogService;
import com.tbl.modules.platform.service.system.RoleService;
import com.tbl.modules.platform.util.DeriveExcel;
import com.tbl.modules.wms.constant.Constant;
import com.tbl.modules.wms.entity.baseinfo.Area;
import com.tbl.modules.wms.service.baseinfo.AreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

import static com.tbl.modules.platform.constant.MenuConstant.area;

/**
 * 库区列表控制层
 * @author zxf
 */
@RestController
@RequestMapping(value = "/area")
public class AreaController extends AbstractController {
    /**
     * 角色
     */
    @Autowired
    private RoleService roleService;
    /**
     * 库区信息
     */
    @Autowired
    private AreaService areaService;
    /**
     * 日志信息
     */
    @Autowired
    private LogService logService;

    /**
     * 跳转库区列表
     * @return MpdelAndView
     */
    @RequestMapping(value = "/toList")
    @ResponseBody
     public ModelAndView toList() {
        ModelAndView mv = this.getModelAndView();
        mv.addObject("operationCode", roleService.selectOperationByRoleId(getSessionUser().getRoleId(), area));
        mv.setViewName("techbloom/baseinfo/area/area_list");
        return mv;
    }

    /**
     * 获取库区列表数据
     * @param queryJsonString 查询条件
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/list.do")
    @ResponseBody
    public Map<String, Object> list(String queryJsonString) {
        Map<String, Object> map = new HashMap<>(3);
        if (!StringUtils.isEmptyString(queryJsonString)) {
            map = JSON.parseObject(queryJsonString);
        }
        PageTbl page = this.getPage();
        PageUtils utils = areaService.getPageList(page, map);
        page.setTotalRows(utils.getTotalCount() == 0 ? 1 : utils.getTotalCount());
        //初始化分页对象
        executePageMap(map, page);
        map.put("rows", utils.getList());
        map.put("total", utils.getTotalPage() == 0 ? 1 : utils.getTotalPage());
        return map;
    }
    
    /**
     * 弹出到编辑页面
     * @param id 主键
     * @return ModelAndView
     */
    @RequestMapping(value = "/toAdd.do")
    @ResponseBody
    public ModelAndView toAdd(Long id) {
        ModelAndView mv = this.getModelAndView();
        mv.setViewName("techbloom/baseinfo/area/area_edit");
        if (id != null && id != 0L) {
            mv.addObject("area", areaService.selectById(id));
        } else {
            Area area = new Area();
            mv.addObject("area", area);
        }
        mv.addObject("edit", Constant.INT_ONE);
        return mv;
    }

    /**
     * 弹出到打印页面
     * @param ids 主键
     * @return ModelAndView
     */
    @RequestMapping(value = "/toPrint.do")
    @ResponseBody
    public ModelAndView toPrint(String ids) {
        ModelAndView mv = this.getModelAndView();
        List<String> images = new ArrayList<>();
        for(String id : ids.split(",")){
            //参数1条形码内容参数2为文字描述
            images.add(BarCodeUtil.getBarCodeImage(id,"文字描述"));
        }
        mv.setViewName("techbloom/baseinfo/area/area_print");
        mv.addObject("imageList", images);
        return mv;
    }
    
    /**
     * 保存库区信息
     * @param area 库区实体
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/saveArea")
    @ResponseBody
    public Map<String, Object> saveArea(Area area) {
        Map<String, Object> map = new HashMap<>(2);
        boolean result=areaService.insertOrUpdate(area);
        map.put("result", result);
        map.put("msg",result?"保存成功！":"保存失败！");
        return map;
    }
    
    /**
     * 删除库区信息
     * @param ids 库区主键
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/deleteArea.do")
    @ResponseBody
    public Map<String, Object> deleteDish(String ids) {
        Map<String, Object> map = new HashMap<>(2);
        boolean result = areaService.deleteBatchIds(Arrays.stream(ids.split(",")).map(Long::parseLong).collect(Collectors.toList()));
        map.put("result", result);
        map.put("msg", result?"删除成功！":"删除失败！");
        return map;
    }

    /**
     * 获取库区列表信息 ：下拉框
     * @param queryString 查询条件
     * @param pageSize 页大小
     * @param pageNo 页码
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/getAreaList")
    @ResponseBody
    public Map<String, Object> getAreaList(String queryString, int pageSize, int pageNo) {
        Map<String, Object> map = new HashMap<>(7);
        PageTbl page = this.getPage();
        map.put("page", pageNo);
        map.put("limit", pageSize);
        String sortOrder = page.getSortorder();
        if (StringUtils.isEmptyString(sortOrder)) {
            sortOrder = "desc";
            page.setSortorder(sortOrder);
        }
        map.put("sidx", page.getSortname());
        map.put("order", page.getSortorder());
        map.put("dname", queryString.toUpperCase());
        //获取库区列表信息 ：下拉框
        map.put("result", areaService.getAreaList(map));
        return map;
    }

    /**
     * 库区基础数据导出Excel
     * @param request HttpServletRequest
     * @param response HttpServletResponse
     */
    @RequestMapping(value = "/materialExcel", method = RequestMethod.POST)
    @ResponseBody
    public void materialExcel(HttpServletRequest request, HttpServletResponse response){
        try {
            String sheetName = "库区列表" + "(" + DateUtils.getDay() + ")";
            response.setHeader("Content-Type", "application/force-download");
            response.setHeader("Content-Type", "application/vnd.ms-excel");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Expires", "0");
            response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
            response.setHeader("Pragma", "public");
            response.setHeader("Content-disposition", "attachment;filename=" + new String(sheetName.getBytes("gbk"),
                    "ISO8859-1") + ".xls");

            Map<String, String> mapFields = new LinkedHashMap<>();
            String [] excelIndexArray = request.getParameter("queryExportExcelIndex").split(",");

            if (excelIndexArray.length==1&&"".equals(excelIndexArray[0])) {
                mapFields.put("code", "库区编号");
                mapFields.put("name", "库区名称");
            }else {
                for (String s : excelIndexArray) {
                    if ("2".equals(s)) {
                        mapFields.put("code", "库区编号");
                    } else if ("3".equals(s)) {
                        mapFields.put("name", "库区名称");
                    }
                }
            }

            DeriveExcel.exportExcel(sheetName, areaService.getExcelList(request.getParameter("ids"), request.getParameter("queryCode"),
                    request.getParameter("queryName")), mapFields, response, "");
            logService.logInsert("库区导出", LogActionConstant.USER_EXPORT, request);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
